package moe.oil.db.service;

import lombok.Setter;
import moe.oil.db.entity.School;
import moe.oil.db.repo.SchoolRepo;
import moe.oil.dto.school.SchoolDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/15 21:58
 * Description:
 *
 * @author - -
 */
@Service
@Setter(onMethod_ = @Autowired)
public class SchoolService implements BaseService {

    private SchoolRepo schoolRepo;

    // 新增学校信息
    public SchoolDTO save(SchoolDTO schoolDTO) {
        return schoolRepo.save(new School(schoolDTO)).convert();
    }

    // 查询全部学校信息
    public List<SchoolDTO> findAll(PageRequest pageRequest) {
        return schoolRepo.findAll(pageRequest).stream().map(School::convert).collect(java.util.stream.Collectors.toList());

    }

    // 根据学校名称查询学校信息
    public SchoolDTO findBySchoolName(String schoolName) {
        return schoolRepo
                .findBySchoolName(schoolName)
                .map(School::convert)
                .orElseThrow(() -> new RuntimeException("没有找到该学校"));
    }

    // 根据学校ID查询学校信息
    public SchoolDTO findBySchoolId(Long schoolId) {
        return schoolRepo.findBySchoolId(schoolId).orElseThrow(() -> new RuntimeException("not found")).convert();
    }

    // 修改学校信息
    public SchoolDTO update(SchoolDTO schoolDTO) {
        return schoolRepo.save(new School(schoolDTO)).convert();
    }

    // 删除学校信息
    @Transactional
    public int delete(Long schoolId) {
        return schoolRepo.deleteBySchoolId(schoolId);
    }
}
